package com.aitaoxue.palx.adapter;

import io.rong.imkit.RongIM;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.api.ApiHttpClient;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.ListBaseAdapter;
import com.aitaoxue.palx.bean.Course;
import com.aitaoxue.palx.db.course.CourseContext;
import com.aitaoxue.palx.db.course.CourseContext.Type;
import com.aitaoxue.palx.ui.AddNewBlogActivity;
import com.aitaoxue.palx.ui.BlogActivity;
import com.aitaoxue.palx.ui.MainActivity;
import com.aitaoxue.palx.ui.dialog.DialogHelper;
import com.aitaoxue.palx.ui.dialog.WaitDialog;
import com.aitaoxue.palx.util.IntentUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;

public class CourseAdapter extends ListBaseAdapter {

	private String courseType;
	private Context mContext;
	private WaitDialog dialog;

	public CourseAdapter(String courseType, Context context) {
		this.courseType = courseType;
		mContext = context;
		dialog = DialogHelper.getWaitDialog((MainActivity) mContext, "请稍等...");
	}

	@Override
	protected View getRealView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null || convertView.getTag() == null) {
			convertView = getLayoutInflater(parent.getContext()).inflate(
					R.layout.list_cell_course_base, null);
			viewHolder = new ViewHolder(convertView);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		final Course course = (Course) _data.get(position);

		viewHolder.number.setText("订单编号: " + course.getOrder_pay_num());
		viewHolder.course_course.setText("订购课程: " + course.getGood_kind_name());
		viewHolder.price.setText("订课价格: " + course.getOrder_pay_num() + "元/小时");
		viewHolder.num.setText("课程数量: " + course.getOrder_num() + "节");
		viewHolder.time.setText("下单时间: " + course.getOrder_date());
		viewHolder.name.setText(course.getUser_name());

		ImageLoader.getInstance().displayImage(
				ApiHttpClient.HEADER_PREFIX + course.getUser_head_thumb(),
				viewHolder.header);

		switch (courseType) {
		case Course.NOT_DEAL: // 待处理
			viewHolder.status.setVisibility(View.GONE);

			viewHolder.btn1.setText("放弃");
			viewHolder.btn1.setTextColor(parent.getContext().getResources()
					.getColor(android.R.color.holo_red_dark));

			viewHolder.btn2.setText("确认接单");
			viewHolder.btn2.setTextColor(parent.getContext().getResources()
					.getColor(R.color.header_bg));

			com.aitaoxue.palx.db.course.Course tmp = CourseContext
					.getInstance().Exist(course.getOrder_id());
			if (tmp == null || tmp.getIsNew() == 1) {
				if (tmp == null) {
					// 插入
					CourseContext.getInstance()
							.saveEntity(course, "6", 1, null);
				}

				viewHolder.newIcon.setVisibility(View.VISIBLE);
			} else {
				viewHolder.newIcon.setVisibility(View.GONE);
			}

			break;
		case Course.DEALING: // 进行中
			viewHolder.status.setText("已完成: " + course.getOrder_finished()
					+ "/" + course.getOrder_num());

			viewHolder.btn1.setText("提醒确认授课");
			viewHolder.btn1.setTextColor(parent.getContext().getResources()
					.getColor(R.color.header_bg));

			viewHolder.btn2.setText("添加课程日志");
			viewHolder.btn2.setTextColor(parent.getContext().getResources()
					.getColor(R.color.header_bg));

			com.aitaoxue.palx.db.course.Course tmp2 = CourseContext
					.getInstance().Exist(course.getOrder_id());
			if (tmp2 == null || tmp2.getIsNew() == 1) {
				if (tmp2 == null) {
					// 插入
					CourseContext.getInstance()
							.saveEntity(course, "1", 1, null);
				}

				viewHolder.newIcon.setVisibility(View.VISIBLE);
			} else {
				viewHolder.newIcon.setVisibility(View.GONE);
			}

			break;
		case Course.DEALED: // 已完结
			viewHolder.status.setText("已完结");

			viewHolder.btn1.setVisibility(View.GONE);

			viewHolder.btn2.setText("查看日志");
			viewHolder.btn2.setTextColor(parent.getContext().getResources()
					.getColor(R.color.header_bg));

			com.aitaoxue.palx.db.course.Course tmp3 = CourseContext
					.getInstance().Exist(course.getOrder_id());
			if (tmp3 == null || tmp3.getIsNew() == 1) {
				if (tmp3 == null) {
					// 插入
					CourseContext.getInstance()
							.saveEntity(course, "2", 1, null);
				}

				viewHolder.newIcon.setVisibility(View.VISIBLE);
			} else {
				viewHolder.newIcon.setVisibility(View.GONE);
			}
			break;
		default:
			break;
		}

		viewHolder.btn1.setOnClickListener(new Btn1ClickListener(course,
				viewHolder));

		viewHolder.btn2.setOnClickListener(new Btn2ClickListener(course,
				viewHolder));

		viewHolder.chat.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (RongIM.getInstance() != null) {
					RongIM.getInstance().startPrivateChat(mContext,
							course.getUser_phone(), "test");
				}
			}
		});

		return convertView;
	}

	static class ViewHolder {

		// 头像
		@InjectView(R.id.course_header)
		ImageView header;
		// 订单编号
		@InjectView(R.id.course_number)
		TextView number;
		// 订购课程
		@InjectView(R.id.course_course)
		TextView course_course;
		// 订课价格
		@InjectView(R.id.course_price)
		TextView price;
		// 课程数量
		@InjectView(R.id.course_num)
		TextView num;
		// 姓名
		@InjectView(R.id.course_name)
		TextView name;
		// 下单时间
		@InjectView(R.id.course_time)
		TextView time;
		// 订单状态
		@InjectView(R.id.course_status)
		TextView status;
		// 按钮1
		@InjectView(R.id.course_btn_1)
		Button btn1;
		// 按钮2
		@InjectView(R.id.course_btn_2)
		Button btn2;
		// 和他聊聊
		@InjectView(R.id.textView1)
		TextView chat;
		// new图标
		@InjectView(R.id.new_order_icon)
		ImageView newIcon;

		public ViewHolder(View view) {
			ButterKnife.inject(this, view);
		}
	}

	private class Btn1ClickListener implements OnClickListener {

		private Course course;
		private ViewHolder viewHolder;

		public Btn1ClickListener(Course course, ViewHolder viewHolder) {
			this.course = course;
			this.viewHolder = viewHolder;
		}

		@Override
		public void onClick(View v) {
			switch (courseType) {
			case Course.NOT_DEAL:
				// 放弃
				dialog.show();
				AitaoXueApi.orderWaive(course.getOrder_id(),
						new AsyncHttpResponseHandler() {

							@Override
							public void onSuccess(int arg0, Header[] arg1,
									byte[] arg2) {
								String res = new String(arg2);

								try {
									JSONObject json = new JSONObject(res);
									String codeMsg = json.getString("codemsg");

									if (codeMsg.equals("success")) {
										_data.remove(course);
										notifyDataSetChanged();

										CourseContext.getInstance()
												.deleteEntity(
														course.getOrder_id());

										dialog.hide();
									}

								} catch (JSONException e) {
									e.printStackTrace();
								}
							}

							@Override
							public void onFailure(int arg0, Header[] arg1,
									byte[] arg2, Throwable arg3) {

							}
						});
				break;
			case Course.DEALING:
				// 提醒确认授课
				dialog.show();

				if (CourseContext.getInstance().isTimeAvailable(
						course.getOrder_id(), System.currentTimeMillis())) {
					dialog.hide();

					// 弹出选项选择框
					AlertDialog.Builder builder = new AlertDialog.Builder(
							mContext);
					View view = LayoutInflater.from(mContext).inflate(
							R.layout.alert_course, null);
					builder.setView(view);
					final AlertDialog alertDialog = builder.create();
					alertDialog.show();
					final EditText num = (EditText) view.findViewById(R.id.num);
					final DatePicker picker = (DatePicker) view
							.findViewById(R.id.datePicker);

					view.findViewById(R.id.btn_ok).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									alertDialog.dismiss();
									int nn = Integer.parseInt(num.getText()
											.toString());

									if (nn < 1 || nn > 4) {
										Toast.makeText(mContext, "课时数必须在1-4之间",
												Toast.LENGTH_SHORT).show();
									} else {
										int y = picker.getYear();
										int m = picker.getMonth() + 1;
										int d = picker.getDayOfMonth();

										dialog.show();
										AitaoXueApi.remainComfirm(
												course.getOrder_id(),
												String.valueOf(nn), y + "-" + m
														+ "-" + d+" 00:00:00",
												new AsyncHttpResponseHandler() {

													@Override
													public void onSuccess(
															int arg0,
															Header[] arg1,
															byte[] arg2) {
														String res = new String(
																arg2);

														try {
															JSONObject json = new JSONObject(
																	res);
															String codeMsg = json
																	.getString("codemsg");
															if (codeMsg
																	.equals("success")) {
																// 提醒成功
																CourseContext
																		.getInstance()
																		.saveNewTime(
																				course.getOrder_id());

																Toast.makeText(
																		mContext,
																		"提醒成功",
																		Toast.LENGTH_SHORT)
																		.show();
															}
														} catch (JSONException e) {
															e.printStackTrace();
														}

														dialog.hide();
													}

													@Override
													public void onFailure(
															int arg0,
															Header[] arg1,
															byte[] arg2,
															Throwable arg3) {
														System.out
																.println("hahha");
													}
												});
									}
								}
							});

					view.findViewById(R.id.btn_cancel).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									alertDialog.dismiss();
								}
							});

				} else {
					dialog.hide();

					Toast.makeText(mContext, "距上次提醒不足一小时", Toast.LENGTH_SHORT)
							.show();
				}
				break;
			default:
				break;
			}

			if (CourseContext.getInstance().isOrderNew(course.getOrder_id())) {
				viewHolder.newIcon.setVisibility(View.GONE);

				CourseContext.getInstance().saveEntity(course, courseType, 0,
						null);

				CourseContext.getInstance().saveType(
						Integer.parseInt(courseType), Type.DELETE);
				// 发送广播,改变订单红点
				Intent broadIntent = new Intent(IntentUtil.PUSH_NEW_ORDER);
				mContext.sendBroadcast(broadIntent);
			}
		}
	}

	private class Btn2ClickListener implements OnClickListener {

		private Course course;
		private ViewHolder viewHolder;

		public Btn2ClickListener(Course course, ViewHolder viewHolder) {
			this.course = course;
			this.viewHolder = viewHolder;
		}

		@Override
		public void onClick(View v) {
			switch (courseType) {
			case Course.NOT_DEAL:
				dialog.show();
				AitaoXueApi.orderEnsure(course.getOrder_id(),
						new AsyncHttpResponseHandler() {

							@Override
							public void onSuccess(int arg0, Header[] arg1,
									byte[] arg2) {
								String res = new String(arg2);

								try {
									JSONObject json = new JSONObject(res);
									String codemsg = json.getString("codemsg");

									if (codemsg.equals("success")) {
										_data.remove(course);
										notifyDataSetChanged();

										CourseContext.getInstance()
												.deleteEntity(
														course.getOrder_id());

										// 确认接单后需改变正在进行
										CourseContext.getInstance().saveType(1,
												Type.ADD);
										// 发送广播,改变订单红点
										Intent broadIntent = new Intent(
												IntentUtil.PUSH_NEW_ORDER);
										broadIntent.putExtra("type", "1");
										mContext.sendBroadcast(broadIntent);

										// 刷新正在进行中页面

										dialog.hide();
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}

							}

							@Override
							public void onFailure(int arg0, Header[] arg1,
									byte[] arg2, Throwable arg3) {
								// TODO Auto-generated method stub

							}
						});
				break;
			case Course.DEALING:
				//添加课程日志
				Intent intent=new Intent(mContext, AddNewBlogActivity.class);
				intent.putExtra("name", course.getUser_name());
				intent.putExtra("orderid", course.getOrder_id());
				mContext.startActivity(intent);
				break;
			case Course.DEALED:
				//查看日志
				Intent intent2=new Intent(mContext, BlogActivity.class);
				intent2.putExtra("orderid", course.getOrder_id());
				mContext.startActivity(intent2);
				break;
			default:
				break;
			}

			if (CourseContext.getInstance().isOrderNew(course.getOrder_id())) {
				viewHolder.newIcon.setVisibility(View.GONE);

				CourseContext.getInstance().saveEntity(course, courseType, 0,
						null);

				CourseContext.getInstance().saveType(
						Integer.parseInt(courseType), Type.DELETE);
				// 发送广播,改变订单红点
				Intent broadIntent = new Intent(IntentUtil.PUSH_NEW_ORDER);
				mContext.sendBroadcast(broadIntent);
			}
		}

	}

}
